/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package respaldomysql;

import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
import java.util.Date;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.*;
/**
 *
 * @author Lolo
 */
public class Inicio extends javax.swing.JFrame {

    private Timer t = new Timer();
    private boolean procesoEjecutado = false;
    private ArrayList<Respaldo> respaldos;

    /**
     * Creates new form Inicio
     */
    public Inicio() {

        respaldos = Respaldo.GetRespaldos();
        initComponents();
//     	Log.registrar(txt,("leerXML: " + new Date(System.currentTimeMillis()) +"\r\n"));
     	
//     	Log.registrar(txt,("setMenu: " + new Date(System.currentTimeMillis()) +"\r\n"));
        setMenu();    
        setState(Frame.ICONIFIED);  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktopPane = new javax.swing.JDesktopPane();
        lbStatus = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txt = new javax.swing.JTextArea();
        lbHora = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        herramientasMenu = new javax.swing.JMenu();
        jMenuItemConfiguracion = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        lbStatus.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        desktopPane.add(lbStatus);
        lbStatus.setBounds(280, 480, 110, 20);

        txt.setColumns(20);
        txt.setRows(5);
        jScrollPane1.setViewportView(txt);

        desktopPane.add(jScrollPane1);
        jScrollPane1.setBounds(0, 380, 770, 120);
        desktopPane.add(lbHora);
        lbHora.setBounds(0, 480, 260, 20);

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");

        openMenuItem.setMnemonic('o');
        openMenuItem.setText("Open");
        fileMenu.add(openMenuItem);

        saveMenuItem.setMnemonic('s');
        saveMenuItem.setText("Save");
        fileMenu.add(saveMenuItem);

        saveAsMenuItem.setMnemonic('a');
        saveAsMenuItem.setText("Save As ...");
        saveAsMenuItem.setDisplayedMnemonicIndex(5);
        fileMenu.add(saveAsMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setMnemonic('e');
        editMenu.setText("Edit");

        cutMenuItem.setMnemonic('t');
        cutMenuItem.setText("Cut");
        editMenu.add(cutMenuItem);

        copyMenuItem.setMnemonic('y');
        copyMenuItem.setText("Copy");
        editMenu.add(copyMenuItem);

        pasteMenuItem.setMnemonic('p');
        pasteMenuItem.setText("Paste");
        editMenu.add(pasteMenuItem);

        deleteMenuItem.setMnemonic('d');
        deleteMenuItem.setText("Delete");
        editMenu.add(deleteMenuItem);

        menuBar.add(editMenu);

        herramientasMenu.setText("Herramientas");

        jMenuItemConfiguracion.setText("Configuración");
        jMenuItemConfiguracion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemConfiguracionActionPerformed(evt);
            }
        });
        herramientasMenu.add(jMenuItemConfiguracion);

        menuBar.add(herramientasMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("Help");

        contentMenuItem.setMnemonic('c');
        contentMenuItem.setText("Contents");
        helpMenu.add(contentMenuItem);

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 771, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void jMenuItemConfiguracionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemConfiguracionActionPerformed
        FrmConfiguracion frm = new FrmConfiguracion(respaldos);
        frm.setVisible(true);
        desktopPane.add(frm);
    }//GEN-LAST:event_jMenuItemConfiguracionActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                //if ("Nimbus".equals(info.getName())) {
                if ("GTK".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Inicio().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem contentMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenu herramientasMenu;
    private javax.swing.JMenuItem jMenuItemConfiguracion;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbHora;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    private javax.swing.JTextArea txt;
    // End of variables declaration//GEN-END:variables

//    private void crearControles() {
//        FlowLayout flowLayout = new FlowLayout();
//        Panel panel = new Panel(flowLayout);
//        flowLayout.setAlignment(FlowLayout.TRAILING);
//        add(panel);
//
//        txt = new TextArea();
//        txt.setEditable(false);
//        panel.add(txt);
//
//        lbEstado = new Label();
//        lbEstado.setText("Detenido");
//        lbEstado.setBackground(Color.RED);
//        panel.add(lbEstado);
//    }

    /**
     * Shutdown procedure when run as an application.
     */
    protected void windowClosed() {
        System.exit(0);
    }

    private void setMenu() {

        menuArchivo();
        menuHerramientas();
    }

    private void menuArchivo() {
        setTitle("RespaldosMySql");


        JMenuItem menuFileCarcarCNF = new JMenuItem();
        menuFileCarcarCNF.setLabel("CarcarCNF");

        // Add action listener.for the menu button
        menuFileCarcarCNF.addActionListener(
                new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                respaldos = Respaldo.GetRespaldos();
                Log.registrar(txt, ("leerXML: " + new Date(System.currentTimeMillis()) + "\r\n"));
            }
        });
        fileMenu.add(menuFileCarcarCNF);
    }

    private void menuHerramientas() {
        JMenuItem menuIniciar = new JMenuItem();

        herramientasMenu.setText("Herramientas");
        menuIniciar.setText("Iniciar");

        // Add action listener.for the menu button
        menuIniciar.addActionListener(
                new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Log.registrar(txt, ("iniciarTimer: " + new Date(System.currentTimeMillis()) + "\r\n"));
                lbStatus.setText("Iniciado");
                lbStatus.setBackground(Color.GREEN);
                iniciarTimer();
            }
        });
        herramientasMenu.add(menuIniciar);

        JMenuItem menuFinalizar = new JMenuItem();

        menuFinalizar.setText("Finalizar");

        // Add action listener.for the menu button
        menuFinalizar.addActionListener(
                new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                lbStatus.setText("Detenido");
                lbStatus.setBackground(Color.RED);
                Log.registrar(txt, ("datenerTimer: " + new Date(System.currentTimeMillis()) + "\r\n"));
                t.cancel();
                t.purge();
            }
        });
        herramientasMenu.add(menuFinalizar);
    }

    private void iniciarTimer() { 
        respaldos = Respaldo.GetRespaldos();
        Log.registrar(txt, ("TimerTask: " + new Date(System.currentTimeMillis()) + "\r\n"));
        TimerTask task;
        task = new TimerTask() {
  public void run() {
      //lbTime.setText(""+ new Date(System.currentTimeMillis()).toString());
      File f;
      f = new File("respaldo1.bat");
      if(f.exists())
          f.delete();
      
      respaldo();
      lbHora.setText(Calendar.getInstance().getTime().toString());
  }
};

        t = new Timer();
        t.scheduleAtFixedRate(task, 0, 1000);
    }

    public void respaldo() {
        ArrayList<String> respaldosList = new ArrayList<String>();
        Date fecha = new Date(Calendar.getInstance().getTime().getYear(),Calendar.getInstance().getTime().getMonth(),Calendar.getInstance().getTime().getDay());
        
        //System.out.println("respaldos.size(): "+ respaldos.size());
        for (int i = 0; i < respaldos.size(); i++) {

            Respaldo r = respaldos.get(i);
                
//            System.out.println(""+ new Date(System.currentTimeMillis()).getHours() + "==" + Integer.parseInt(r.getHora().split(":")[0]));
//            System.out.println(""+ new Date(System.currentTimeMillis()).getMinutes() + "==" + Integer.parseInt(r.getHora().split(":")[1]));
//            if (new Date(System.currentTimeMillis()).getHours() == Integer.parseInt(r.getHora().split(":")[0])
//                    && new Date(System.currentTimeMillis()).getMinutes() == Integer.parseInt(r.getHora().split(":")[1])
//                    && !procesoEjecutado) {
//            System.out.println(""+ r.getDiaUltimaEjecucion() + " " + fecha);
//            System.out.println(""+ r.getHora().split(":")[0] + " : " + r.getHora().split(":")[1]);
//            System.out.println(""+ fecha.before(r.getDiaUltimaEjecucion()));
            if(fecha.before(r.getDiaUltimaEjecucion()) && 
                    Calendar.getInstance().getTime().getHours() == Integer.parseInt(r.getHora().split(":")[0]) &&
                    Calendar.getInstance().getTime().getMinutes() == Integer.parseInt(r.getHora().split(":")[1])){
                r.setDiaUltimaEjecucion(fecha);
                System.out.println("ejecutar " + r.getId());
                respaldosList.add(
                        "mysqldump --user=" + r.getUsuario()
                        + " --password=" + r.getPassword()
                        + " -R -f " + r.getBd()
                        + "> " + r.getDirectorio()
                        + r.getBd()
                        + "_"
                        + System.currentTimeMillis() + ".SQL");
                Log.registrar(txt, ("Eje: " + new Date(System.currentTimeMillis()) + "\r\n"));
                Log.registrar(txt, r.getBd());
                System.out.println(
                        "mysqldump --user=" + r.getUsuario()
                        + " --password=" + r.getPassword()
                        + "  " + r.getBd()
                        + "> " + r.getDirectorio()
                        +  r.getBd()
                        + "_"
                        + System.currentTimeMillis() + ".SQL");
                String path = "respaldo1"+System.currentTimeMillis()+".bat";
                File f;
                f = new File(path);
                try {
                    FileWriter w = new FileWriter(f);
                    BufferedWriter bw = new BufferedWriter(w);
                    PrintWriter wr = new PrintWriter(bw);
                    wr.write("D:\r\n");
                    wr.write("cd mysql/bin\r\n");
                    for (int x = 0; x < respaldosList.size(); x++) {
                        wr.write(respaldosList.get(x) + "\r\n");
                    }

                    wr.write("exit");
                    wr.close();
                    bw.close();
                } catch (Exception e) {
                    Log.registrar(txt, "ERROR linea 392: " + e.getMessage() + "\r\n");
                    System.out.println(e);
                }

                try {
                    Runtime rt = Runtime.getRuntime();
                    Process pr = rt.exec(new String[]{"\"" + new File("").getAbsolutePath() + "\\" + path + "\""}, null, new File("").getParentFile());
                    
                } catch (Exception e) {
                    Log.registrar(txt, "ERROR linea 398: " + e.getMessage() + "\r\n");
                    System.out.println(e);
                }
                System.out.println("SI");
            }else if ((new Date(System.currentTimeMillis()).getHours() == Integer.parseInt(r.getHora().split(":")[0])
                    && new Date(System.currentTimeMillis()).getMinutes() != 
                        Integer.parseInt(r.getHora().split(":")[1])) && procesoEjecutado){
                System.out.println("NO");
                procesoEjecutado = false;
            }            
        }
    }
}